<script setup>
import { onMounted, ref, nextTick } from 'vue'
import WelfareItem from '@/components/WelfareItem.vue'
import {
  reqChangeWelfareStatus,
  reqGetWelfareList,
  reqGetWelfareOrder,
  reqGetWelfarePrize,
  reqGetWelfareJoin,
  reqGetWelfareOrderList,
  reqAddWelfare,
  reqGetPrizeList,
  reqAddWelfarePrize
} from '@/api/welfare/index.js'
import { showToast } from 'vant'
import { watch, onBeforeUpdate } from 'vue'

const welfareList = ref([])
const loading = ref(false)
const page = ref(1)
const total = ref(0)
const refreshing = ref(false)
const showControl = ref(false)
const actions = [
  { name: '赏品信息' },
  { name: '获奖记录' },
  { name: '参与人员' },
  { name: '福利屋订单' }
]
const currentWelfareId = ref(0)
const prizeLoading = ref(false)
const prizeList = ref([])
const dataPage = ref(1)
const dataTotal = ref(0)
const showDialog = ref('')
const showOrder = ref(false)
const orderRefreshing = ref(false)
const searchValue = ref('')
const vipType = ref('')
const typeList = [
  { value: '', text: '全部' },
  { value: 1, text: '普通用户' },
  { value: 2, text: '主播' },
  { value: 3, text: '推广员' }
]
const isShowAdd = ref(false)
const packetParams = ref({
  name: '',
  word_command: '',
  room_password: '',
  start_at: '',
  amount: '',
  begin_reward_at: '',
  begin_reward_num: '',
  content: ''
})
const showPicker = ref(false)
const pickerType = ref(0)
const isShowAddPrize = ref(false)

const checked = ref([])
const checkboxRefs = ref([])
const toggle = (index) => {
  checkboxRefs.value[index].toggle()
}

onBeforeUpdate(() => {
  checkboxRefs.value = []
})

const onLoadMore = () => {
  getWelfareList()
}

onMounted(() => {
  refreshing.value = true
  getWelfareList()
})

const getWelfareList = async () => {
  try {
    const result = await reqGetWelfareList({
      page: page.value,
      user_id: searchValue.value,
      type: vipType.value
    })
    if (result.code === 200) {
      if (page.value === 1) {
        welfareList.value = result.data.data
      } else {
        welfareList.value = [...welfareList.value, ...result.data.data]
      }
      total.value = result.data.total
      page.value++
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

const onRefresh = () => {
  page.value = 1
  total.value = 0
  refreshing.value = true
  getWelfareList()
}

const changeStatus = async ({ id, status }) => {
  const welfare = welfareList.value.find((item) => item.id === id)
  const result = await reqChangeWelfareStatus(id, { status: status ? 1 : 0 })
  if (result.code === 200) {
    welfare.status = status ? 1 : 0
    showToast({
      type: 'success',
      message: '操作成功'
    })
  } else {
    showToast({
      type: 'fail',
      message: '操作失败'
    })
  }
}

const onShowControl = (id) => {
  dataPage.value = 1
  dataTotal.value = 0
  showControl.value = true
  currentWelfareId.value = id
  searchValue.value = ''
}

const onSelect = (e) => {
  const index = typeof e === 'number' ? e : actions.indexOf(e)
  showDialog.value = index
  prizeList.value = []
  prizeLoading.value = true
  getPrizeList(index)
}

const getPrizeList = async (index) => {
  try {
    let result
    switch (index) {
      case 0:
        result = await reqGetWelfarePrize({
          wealRoomsPrizesId: currentWelfareId.value,
          page: dataPage.value
        })
        break
      case 1:
        result = await reqGetWelfareOrder(currentWelfareId.value, {
          page: dataPage.value
        })
        break
      case 2:
        result = await reqGetWelfareJoin(currentWelfareId.value, {
          page: dataPage.value
        })
        break
      case 3:
        showOrder.value = true
        nextTick(() => {
          orderRefreshing.value = true
        })
        result = await reqGetWelfareOrderList({
          page: dataPage.value,
          userId: searchValue.value,
          type: vipType.value
        })
        break
      case 4:
        result = await reqGetPrizeList({ page: dataPage.value })
        break
      default:
        break
    }
    if (!result) return
    if (result.code === 200) {
      if (dataPage.value === 1) {
        prizeList.value = result.data.data
      } else {
        prizeList.value.push(...result.data.data)
      }
      dataTotal.value = result.data.total
      dataPage.value++
    }
  } finally {
    prizeLoading.value = false
    orderRefreshing.value = false
  }
}

const onOrderRefresh = () => {
  dataPage.value = 1
  dataTotal.value = 0
  // orderRefreshing.value = true
  getPrizeList(3)
}

const onSearch = () => {
  if (showOrder.value) {
    onOrderRefresh()
  } else {
    onRefresh()
  }
}

watch(searchValue, (newVal) => {
  if (!newVal.trim()) {
    onSearch()
  }
})

const addOfficeWelfare = () => {
  isShowAdd.value = true
  Object.assign(packetParams.value, {
    name: '',
    word_command: '',
    room_password: '',
    start_at: '',
    amount: '',
    begin_reward_at: '',
    begin_reward_num: '',
    content: ''
  })
}

const handleAddPacket = async () => {
  const result = await reqAddWelfare(packetParams.value)
  if (result.code === 200) {
    onRefresh()
  } else {
    showToast({ type: 'fail', message: result.msg })
  }
}

const currentDate = ref(['2022', '06', '01'])
const currentTime = ref(['12', '00'])

const onConfirm = () => {
  showPicker.value = false
  const str = `${currentDate.value.join('-')}T${currentTime.value.join(':')}:00.000Z`
  if (pickerType.value === 1) {
    packetParams.value.begin_reward_at = str
  } else {
    packetParams.value.start_at = str
  }
}

const onCancel = () => {
  showPicker.value = false
}

const setPickerType = (val) => {
  pickerType.value = val
  showPicker.value = true
  const date = new Date()
  currentDate.value = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
}

const handleAddPrize = () => {
  showDialog.value = ''
  isShowAddPrize.value = true
  dataPage.value = 1
  dataTotal.value = 0
  onSelect(4)
}

const addPrize = async () => {
  const result = await reqAddWelfarePrize({
    wealRoomsPrizesId: currentWelfareId.value,
    prize: checked.value
  })

  checked.value = []

  showToast({ type: 'text', message: result.msg })
}
</script>

<template>
  <div class="welfare-container">
    <van-search
      v-model="searchValue"
      show-action
      clearable
      placeholder="请输入用户id"
      @search="onSearch"
      clear-trigger="always"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <van-dropdown-menu v-if="showOrder">
      <van-dropdown-item @change="onOrderRefresh" v-model="vipType" :options="typeList" />
    </van-dropdown-menu>
    <van-button type="primary" @click="addOfficeWelfare">添加官方福利屋</van-button>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" v-if="!showOrder">
      <van-list
        v-model:loading="loading"
        :finished="page * 10 >= total"
        finished-text="没有更多了"
        @load="onLoadMore"
      >
        <WelfareItem
          @showControl="onShowControl(welfare.id)"
          @change-status="changeStatus"
          v-for="welfare in welfareList"
          :key="welfare.id"
          :welfare="welfare"
        />
      </van-list>
      <van-back-top bottom="10vh" />
    </van-pull-refresh>
    <div v-else>
      <van-pull-refresh v-model="orderRefreshing" style="height: 100%" @refresh="onOrderRefresh">
        <div class="header" style="padding: 10px">
          <van-button @click="showOrder = false" type="primary">返回</van-button>
        </div>
        <van-list
          v-model:loading="prizeLoading"
          @load="getPrizeList(3)"
          :finished="dataPage * 10 >= dataTotal"
          finished-text="没有更多了"
        >
          <div class="prize-item" v-for="item in prizeList" :key="item.id">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <UserInfo
                :nickname="item.nickname"
                :id="item.user_id"
                :avatar="item.avatar"
              ></UserInfo>
              <span
                >￥{{ item.price }} {{ item.level_name }} {{ item.status_name }} 赠送:{{
                  item.give_user_id
                }}</span
              >
            </div>
            <div>房间名:{{ item.weal_rooms_name }} ID:{{ item.weal_rooms_id }}</div>
            <div style="font-weight: bold">{{ item.weal_rooms_prizes_name }}</div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
    <van-action-sheet
      v-model:show="showControl"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @select="onSelect"
    />
    <van-dialog
      title="赏品信息"
      @cancel="showDialog = ''"
      show-cancel-button
      cancel-button-text="关闭"
      confirm-button-text="添加"
      @confirm="handleAddPrize"
      :show="showDialog === 0"
    >
      <van-list
        style="max-height: 50vh; overflow-y: scroll"
        @load="getPrizeList(0)"
        v-model:loading="prizeLoading"
        :finished="dataPage * 10 >= dataTotal"
        finished-text="没有更多了"
      >
        <div class="prize-item" v-for="prize in prizeList" :key="prize.id">
          <div>{{ prize.name }}</div>
          <div>￥{{ prize.price }} {{ prize.level_name }}</div>
        </div>
      </van-list>
    </van-dialog>

    <van-dialog title="获奖记录" @confirm="showDialog = ''" :show="showDialog === 1">
      <van-list
        style="max-height: 50vh; overflow-y: scroll"
        @load="getPrizeList(1)"
        v-model:loading="prizeLoading"
        :finished="dataPage * 10 >= dataTotal"
        finished-text="没有更多了"
      >
        <div class="prize-item flex" v-for="order in prizeList" :key="order.id">
          <UserInfo
            :nickname="order.nickname"
            :id="order.user_id"
            :avatar="order.avatar"
          ></UserInfo>
          <div style="margin-left: 10px; flex: 1; font-size: 13px">
            <div>{{ order.weal_rooms_prizes_name }}</div>
            <div>{{ order.price }} {{ order.level_name }}</div>
          </div>
        </div>
      </van-list>
    </van-dialog>

    <van-dialog title="参与记录" @confirm="showDialog = ''" :show="showDialog === 2">
      <van-list
        style="max-height: 50vh; overflow-y: scroll"
        @load="getPrizeList(2)"
        v-model:loading="prizeLoading"
        :finished="dataPage * 10 >= dataTotal"
        finished-text="没有更多了"
      >
        <div class="prize-item" v-for="join in prizeList" :key="join.id">
          <UserInfo :nickname="join.nickname" :avatar="join.avatar" :id="join.id"></UserInfo>
        </div>
      </van-list>
    </van-dialog>
    <van-dialog
      title="添加官方福利屋"
      show-cancel-button
      v-model:show="isShowAdd"
      @confirm="handleAddPacket"
    >
      <van-field
        v-model="packetParams.name"
        type="text"
        label="名称"
        placeholder="福利屋名称"
        input-align="right"
      />
      <van-field
        v-model="packetParams.amount"
        type="number"
        label="金额"
        placeholder="请输入消费金额"
        input-align="right"
      />
      <van-field
        v-model="packetParams.word_command"
        type="text"
        label="口令"
        placeholder="请输入口令"
        input-align="right"
      />
      <van-field
        v-model="packetParams.room_password"
        type="text"
        label="密码"
        placeholder="请输入密码"
        input-align="right"
      />
      <van-field
        v-model="packetParams.begin_reward_num"
        type="number"
        label="人数"
        placeholder="请输入开赏人数"
        input-align="right"
      />
      <van-field
        v-model="packetParams.content"
        type="text"
        label="介绍"
        placeholder="请输入介绍"
        input-align="right"
      />
      <van-cell
        title="开赏时间"
        :value="packetParams.begin_reward_at || '点击选择'"
        @click="setPickerType(1)"
      ></van-cell>
      <van-cell
        title="消费时间"
        :value="packetParams.start_at || '点击选择'"
        @click="setPickerType(2)"
      >
      </van-cell>
    </van-dialog>
    <van-dialog v-model:show="showPicker" :show-confirm-button="false">
      <van-picker-group
        title="预约日期"
        :tabs="['选择日期', '选择时间']"
        @confirm="onConfirm"
        @cancel="onCancel"
      >
        <van-date-picker v-model="currentDate" />
        <van-time-picker v-model="currentTime" />
      </van-picker-group>
    </van-dialog>
    <van-dialog
      title="添加赏品"
      v-model:show="isShowAddPrize"
      show-cancel-button
      @confirm="addPrize"
    >
      <van-list
        style="max-height: 50vh; overflow-y: scroll"
        @load="getPrizeList(4)"
        v-model:loading="prizeLoading"
        :finished="dataPage * 10 >= dataTotal"
        finished-text="没有更多了"
      >
        <van-checkbox-group v-model="checked">
          <van-cell-group>
            <van-cell
              v-for="(item, index) in prizeList"
              clickable
              :key="item.id"
              :title="`${item.id}`"
              :label="`${item.price}`"
              @click="toggle(index)"
            >
              <template #icon>
                <van-image :src="item.image" width="50" fit="cover" />
              </template>
              <template #right-icon>
                <van-checkbox :name="item" :ref="(el) => (checkboxRefs[index] = el)" @click.stop />
              </template>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </van-list>
    </van-dialog>
  </div>
</template>

<style scoped lang="less">
.prize-item {
  padding: 10px;
  font-size: 14px;
  border-bottom: 1px solid #f5f5f5;

  &.flex {
    display: flex;
  }
}
</style>
